package pc

import (
	. "chess_platform/internal/common"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

//新建操作日志
func newOperationLog(data map[string]interface{}) (int64, error) {
	o := NewDBOrm(DBChessCenter)
	values, sql := InsertSql(TableOperationLog, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

func NewOperationLog(uid, module, typ int64, ip, msg string, detail map[string]interface{}) {
	dt, _ := json.Marshal(detail)
	data := map[string]interface{}{
		"uid":         uid,
		"ip":          ip,
		"module":      module,
		"type":        typ,
		"msg":         msg,
		"detail":      string(dt),
		"create_time": time.Now().Unix(),
	}
	newOperationLog(data)
}

//列出操作日志
func ListOperationLog(p ListParams, t ListDayParams, uid, typ, module int64,
	name string, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := " 1=1 "
	if uid != 0 {
		where = fmt.Sprintf("o.uid = %v", uid)
	}
	if typ != 0 {
		where = where + fmt.Sprintf(" AND o.type = %v", typ)
	}
	if module != 0 {
		where = where + fmt.Sprintf(" AND o.module = %v", module)
	}
	if name != "" {
		where = where + fmt.Sprintf(" AND u.name LIKE '%v' ", "%"+name+"%")
	}

	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND o.create_time >= %v AND o.create_time < %v", t.StartTime, t.EndTime)
	}

	sql := fmt.Sprintf(`
		SELECT
			o.*,u.name
		FROM
			%v AS o
		LEFT JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE
			%v
		ORDER BY
			id DESC
		LIMIT ?,?
		`, TableOperationLog, TablePcUser, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var log []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&log)
	if err != nil {
		return nil, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS o
			LEFT JOIN %v AS u ON o.uid = u.uid WHERE %v`, TableOperationLog, TablePcUser, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return log, count, err
}
